#include "BlockingQueueCore.hh"

BlockingQueueCore::BlockingQueueCore(Signal* AssignedSignal)
{
	if (!State)
		return;
	
	State = false;
	
	SignalOfInputEvent = AssignedSignal;
	checkNullFV(SignalOfInputEvent, "Bad parameter.");
	
	State = true;
}

ResultOf BlockingQueueCore::enqueue(void* Object)
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_ERROR;
	}
	
	ResultOf Result;
	Result = Queue::enqueue(Object);
	checkErrorWR(Result, "Fail Queue::enqueue.");
	
	Result = SignalOfInputEvent->post();
	checkErrorWR(Result, "Fail SignalOfInputEvent->post.");
	
	return RETURN_OK;
}

void* BlockingQueueCore::dequeue()
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return NULL;
	}
	
	void* Return;
	dequeue(&Return);
	return Return;
}

ResultOf BlockingQueueCore::dequeue(void** ReturnData)
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_PARAM_ERROR;
	}
	
	ResultOf Result;
	Result = SignalOfInputEvent->pend();
	switch (Result)
	{
		case RETURN_OK:
			break;
			
		default:
			notifyError(Result, "Fail SignalOfInputEvent->pend.");
		
		case RETURN_BLOCK:
		case RETURN_TIMEOUT:
			*ReturnData = NULL;
			return Result;
	}
	
	*ReturnData = Queue::dequeue();
	return RETURN_OK;
}

ResultOf BlockingQueueCore::fill()
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_ERROR;
	}
	
	ResultOf Result;
	Result = SignalOfInputEvent->allowWaiting();
	checkErrorWR(Result, "Fail SignalOfInputEvent->allowWaiting.");
	
	Result = Queue::fill();
	checkErrorWR(Result, "Fail Queue::fill.");
	
	return RETURN_OK;
}

ResultOf BlockingQueueCore::flush()
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_ERROR;
	}
	
	ResultOf Result;
	Result = Queue::flush();
	checkErrorWR(Result, "Fail Queue::flush.");
	
	Result = SignalOfInputEvent->preventWaiting();
	checkErrorWR(Result, "Fail SignalOfInputEvent->preventWaiting.");
	
	Result = SignalOfInputEvent->release();
	checkErrorWR(Result, "Fail SignalOfInputEvent->release.");
	
	return RETURN_OK;
}

ResultOf BlockingQueueCore::release()
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_ERROR;
	}
	
	ResultOf Result;
	Result = SignalOfInputEvent->release();
	checkErrorWR(Result, "Fail SignalOfInputEvent->release.");
	
	return RETURN_OK;
}

Number BlockingQueueCore::tellNumOfBlocking()
{
	if (!State)
	{
		fprintf(stderr, "This instance(%x) is not available.\n", (Number)this);
		return RETURN_ERROR;
	}
	
	return SignalOfInputEvent->tellWaiting();
}
